<template>
<div class="amend" v-loading="loading">
  <Add></Add>
  <el-row class="my_title">
    <el-col :span="12" class="left">
      <span class="title" v-show="!lookStatus">子问题管理</span>
      <span class="title" v-show="lookStatus">关系图</span>
      <!--<el-button  v-show="lookStatus" icon="el-icon-date" style="margin-left: 10px" type="success" round @click="toggleStyle">{{!lookStatus2 ? '切换为和弦布局' : '切换为力导向布局'}}</el-button>-->
      <!--<el-button  v-show="lookStatus" icon="el-icon-refresh" style="margin-left: 10px"  round @click="goRe">还原</el-button>-->
    </el-col>
    <el-col :span="12" class="right">
      <el-button icon="el-icon-circle-plus" type="primary" @click="goAddPage">增加子问题</el-button>
      <el-button icon="el-icon-view" type="success" @click="showGraph">{{lookStatus ? '查看列表' : '查看关系图'}}</el-button>
    </el-col>
  </el-row>
  <!--子问题-->
  <el-table
    v-show="!lookStatus"
    ref="muTable"
    :data="tableData"
    style="width: 100%"
    @row-click="checkRow"
    @highlight-current-row="false"
    :highlightCurrentRow="false"
  >
    <el-table-column type="expand">
      <template slot-scope="props">
        <el-form label-position="left" inline class="demo-table-expand c-tag">
          <el-form-item label="问题" v-for="(o ,ii) in props.row.s_qstarr" :key="ii" style="width: 100%;">
            <el-popover trigger="hover" placement="top">
              <p  style="max-width: 800px">关键词:
                <el-tag style="margin: 4px" v-for="(n,inde) in o.keywords.split(' ')" :key="inde">
                  {{n.length > 20 ? (n.substring(0,20) + '...') : n}}
                </el-tag>
              </p>
              <div slot="reference" class="name-wrapper">
                <span>
                  {{o.qustion}}
                  <!--{{o.qustion.length > 80 ? (o.qustion.substring(0,80) + '...') : o.qustion}}-->
                </span>
                <i class="el-icon-question"></i>
              </div>
            </el-popover>
          </el-form-item>
          <el-form-item label="答案" style="width: 100%;">
            <span>
              {{props.row.s_answer}}
              <!--{{props.row.s_answer.length > 80 ? (props.row.s_answer.substring(0,80) + '...') : props.row.s_answer}}-->
            </span>
          </el-form-item>
          <el-form-item label="标签" style="width: 100%">
            <el-tag style="margin-left: 5px" v-for="tt in props.row.s_tags" :type=" !tt ? 'info' : ''" :key="tt">{{tt ? tt : '无标签'}}</el-tag>
          </el-form-item>
          <el-form-item label="关键词" style="width: 100%;">
            <el-tag type="success" style="margin-left: 5px" v-for="tt in props.row.s_keywords.split(',')" :key="tt">
              {{tt.length > 20 ? (tt.substring(0,20) + '...') : tt}}
            </el-tag>
          </el-form-item>
          <el-form-item label="ID">
            <span>{{ props.row._id }}</span>
          </el-form-item>
          <el-form-item label="父级 ID">
            <el-tag type="warning" v-for="tt in props.row.s_pids" :key="tt" v-if="tt">
              {{tt}}
            </el-tag>
          </el-form-item>
        </el-form>
      </template>
    </el-table-column>
    <el-table-column
      label="问题">
      <template slot-scope="scope">
        <div class="drop-text">
          {{scope.row.s_qstarr[0].qustion}}
          <!--{{scope.row.s_qstarr[0].qustion.length > 30 ? (scope.row.s_qstarr[0].qustion.substring(0,30) + '...') : scope.row.s_qstarr[0].qustion}}-->
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="答案">
      <template slot-scope="scope">
        <div class="drop-text">
          {{scope.row.s_answer}}
          <!--{{scope.row.s_answer.length > 30 ? (scope.row.s_answer.substring(0,30) + '...') : scope.row.s_answer}}-->
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="标签"
      prop="tags"
    >
      <template slot-scope="scope">
        <section>
        <el-tag v-for="t in scope.row.s_tags.slice(0,2)" :key="t" style="margin: 4px 10px 4px 0;" :type=" !t ? 'info' : ''">
          {{t ? t : '无标签'}}
        </el-tag>
        </section>
      </template>
    </el-table-column>
    <el-table-column
      label="关键字"
      prop="s_keywords">
      <template slot-scope="scope">
        <section>
          <el-tag v-for="t in scope.row.s_keywords.split(',').slice(0,2)" :key="t" style="margin: 4px 10px 4px 0;" type="success">
            {{t.length > 8 ? (t.substring(0,8) + '...') : t}}
          </el-tag>
        </section>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      fixed="right"
      width="220"
    >
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="warning"
          @click="untieRow(scope.$index, scope.row)">解绑
        </el-button>
        <el-button
          size="mini"
          @click="editRow(scope.$index, scope.row)">编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--分页-->
  <el-pagination
    v-show="!lookStatus"
    class="my_top"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-size="10"
    layout="total, prev, pager, next, jumper"
    :total="pageNumber"
    background>
  </el-pagination>
  <!--关系图-->
  <el-tooltip class="item" effect="dark" content="双击前往编辑" placement="top">
    <div v-show="lookStatus" id="test2" :style="{width: '100%',height: '700px',border: '1px solid #fff'}"></div>
  </el-tooltip>
</div>
</template>
<script>
import Add from './add'
import { qa, unQa } from '../api/getData'
import ElTag from 'element-ui/packages/tag/src/tag'
import ElFormItem from 'element-ui/packages/form/src/form-item'

export default {
  components: {
    ElFormItem,
    ElTag,
    Add
  },
  name: 'amend',
  data: function () {
    return {
      lookStatus2: false,
      lookStatus: false,
      errNumber: {},
      pageNumber: 10,
      loading: true,
      tableData: [],
      filTag: [],
      currentPage: 1,
      addData: {
        name: 'addData'
      },
      EDataArr: [{
        x: 100,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }, {
        x: 300,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }, {
        x: 500,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }],
      EData: {
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            type: 'graph',
            layout: 'none',
            symbolSize: (value = 15) => {
              return value
            },
            roam: true, // 鼠标缩放及平移
            legendHoverLink: true,
            focusNodeAdjacency: true, // 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点
            label: {
              normal: {
                show: true, // 控制非高亮时节点名称是否显示
                position: 'right',
                fontSize: 16,
                color: '#6062666b',
                backgroundColor: '#fff',
                padding: 5,
                borderRadius: 5,
                textStyle: {
                  fontSize: 16,
                  color: '#606266'
                }
              }
            },
            itemStyle: {
              color: '#409EFF'
            },
            force: {
              repulsion: 3000,
              edgeLength: 300
            },
            edgeSymbol: ['circle', 'arrow'],
            edgeSymbolSize: [1, 15], // 箭头的大小
            categories: [
              {
                itemStyle: {
                  color: '#ddceff'
                },
                label: {
                  normal: {
                    show: true, // 控制非高亮时节点名称是否显示
                    position: 'left'
                  }
                }
              }, {
                itemStyle: {
                  color: '#fffaa2'
                },
                label: {
                  normal: {
                    show: true, // 控制非高亮时节点名称是否显示
                    position: 'top'
                  }
                }
              }, {
                itemStyle: {
                  color: '#cfffe4'
                }
              }
            ],
            edgeLabel: {
              normal: {
                show: true,
                color: 'transparent'
              },
              emphasis: {
                textStyle: {
                  color: 'yellow',
                  fontSize: 18 // 边节点显示的字体大小
                }
              }
            }, // 节点信息
            data: [],
            links: [],
            lineStyle: {
              normal: {
                show: true,
                color:
                  {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0, color: 'red' // 0% 处的颜色
                      }, {
                        offset: 1, color: 'blue' // 100% 处的颜色
                      }
                    ],
                    globalCoord: false // 缺省为 false
                  }
                // curveness: 0.2
              },
              emphasis: {
                color: 'red',
                width: 3,
                type: 'dashed' // 虚线

              }
            },
            tooltip:
              {
                position: 'bottom', // 悬浮时显示的位置
                backgroundColor: '#fff',
                border: '1px solid #ebeef5',
                borderRadius: 5,
                fontSize: 14,
                textStyle: {
                  fontSize: 14,
                  color: '#606266'
                },
                formatter: function (params) { // 悬浮提示框显示的内容
                  if (params.data.islink) {
                    return `

                      <div class="my-tip">
    <div class="tip-item">
      <span>父级:</span>
      <span>${params.data.source}</span>
    </div>
    <div class="tip-item">
      <span>子级:</span>
      <span>${params.data.target}</span>
    </div>
  </div>`
                  } else if (params.data.isnode) {
                    return `
<div class="my-tip">
    <div class="tip-item">
      <span>问&nbsp;&nbsp;&nbsp;题:</span>
      <span>${params.data.name}</span>
    </div>
    <div class="tip-item">
      <span>关键字:</span>
      <span>${params.data.tip}</span>
    </div>
  </div> `
                  }
                }
              } // 悬浮时的提示框，不设置时是随鼠标移动

          }
        ]
      }
    }
  },
  created: function () {}, // 创建时
  beforeMount: function () {}, // 挂载之前
  mounted: function () {
    this.getSList()
    /* 绘制图表 */
    this.getIData(this.$route.params.id)
    let myChart2 = this.$echarts.init(document.getElementById('test2'))
    setTimeout(() => {
      document.getElementById('test2').style.width = document.querySelector('.amend').clientWidth + 'px'
      myChart2.resize()
    })
    // 绘制图表
    /* 单击展示更多 */
    // myChart2.on('click', params => {
    //   this.getIData(params.data.tid)
    // })
    window.onresize = function () {
      myChart2.resize()
    }
    myChart2.on('dblclick', params => {
      if (!params.data.tid) { return false }
      document.querySelector('main').scrollTop = 0
      this.lookStatus = false
      this.EDataArr = []
      this.EDataArr = [{
        x: 100,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }, {
        x: 300,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }, {
        x: 500,
        y: 200,
        min: 200,
        max: 200,
        step: 60
      }]
      setTimeout(() => {
        this.$router.push('/amend/' + params.data.tid)
      }, 500)
    })
  }, // 挂载之后
  beforeUpdate: function () {}, // 数据更新时调用,在渲染之前
  updated: function () {}, // 数据更新后,渲染后调用(禁止)
  beforeDestroy: function () {}, // 实例销毁前调用,解绑中间层的数据传输
  destroyed: function () {}, // 实例销毁后调用
  watch: {
    // 如果路由有变化，会再次执行该方法
    '$route': 'upData'
  },
  methods: {
    goRe () {
      this.EData.series[0].links = []
      this.EData.series[0].data = []
      /* 绘制图表 */
      this.getIData(this.$route.params.id)
    },
    upData () {
      this.getSList()
      this.EData.series[0].links = []
      this.EData.series[0].data = []
      /* 绘制图表 */
      this.getIData(this.$route.params.id)
    },
    checkRow (row, event, column) {
      if (column.label === '操作') {
        return false
      }
      this.$refs.muTable.toggleRowExpansion(row)
    },
    untieRow (index, row) {
      unQa({
        id: row._id,
        pid: this.$route.params.id,
        flagState: ''
      }).then(({data}) => {
        let flag = data.msg === 'success'
        if (flag) { this.tableData.splice(index, 1) }
        this.$notify({
          title: flag ? '解绑成功' : '解绑失败',
          position: 'top-right',
          message: flag ? '已成功解除绑定关系' : data.msg,
          type: flag ? 'success' : 'error'
        })
      }).catch(err => {
        this.$notify({
          title: '解绑失败',
          position: 'top-right',
          message: err,
          type: 'error'
        })
      })
    },
    editRow (index, row) {
      this.$router.push('/amend/' + row._id)
    },
    handleCurrentChange (val) {
      this.getSList(val, false)
    },
    /* 获取子问题 */
    getSList (n = 1, f = true) {
      if (this.errNumber['getSList'] > 4) {
        return this.$notify({
          title: '获取数据失败,请手动刷新重试',
          position: 'top-right',
          message: '请刷新重试',
          type: 'error'
        })
      }
      qa({id: this.$route.params.id, pagenum: String(n)}).then(({data}) => {
        if (Object.keys(data).includes('msg')) {
          this.$notify({
            title: '获取数据失败,正在重试',
            position: 'top-right',
            message: data.msg || '请重试',
            type: 'error'
          })
          this.errNumber['getSList'] = (this.errNumber['getSList'] || 0) + 1
          return setTimeout(() => {
            return this.getSList(n)
          }, 1000)
        } else {
          this.loading = false
          this.tableData = data[0].clist
          if (f) {
            this.$bus.$emit('addData', data[0].list)
          }
          this.pageNumber = data[0].ccount
          let tempArr = []
          this.tableData.forEach(v => {
            v.s_tags.forEach(s => {
              if (!tempArr.includes(s)) {
                tempArr.push(s)
              }
            })
          })
          this.filTag = tempArr.map(v => {
            let obj = {
              value: v,
              text: v || '无标签'
            }
            return obj
          })
        }
      }).catch(err => {
        this.loading = false
        this.$notify({
          title: '获取数据失败,正在重试',
          position: 'top-right',
          message: err || '请重试',
          type: 'error'
        })
        this.errNumber['getSList'] = (this.errNumber['getSList'] || 0) + 1
        return setTimeout(() => {
          return this.getSList(n)
        }, 2000)
      })
    },
    filterTag (value, row) {
      return row.s_tags.includes(value)
    },
    goAddPage () {
      this.$router.push('/add/' + this.$route.params.id)
    },
    showGraph () {
      this.lookStatus = !this.lookStatus
    },
    createEcharts () {
      // 绘制图表
      let myChart2 = this.$echarts.init(document.getElementById('test2'))
      this.$nextTick(() => {
        myChart2.setOption(this.EData)
      })
    },
    toggleStyle () {
      let s = !this.lookStatus2 ? 'circular' : 'force'
      this.lookStatus2 = !this.lookStatus2
      this.EData.series[0].layout = s
      // 绘制图表
      let myChart2 = this.$echarts.init(document.getElementById('test2'))
      this.$nextTick(() => {
        myChart2.setOption(this.EData)
      })
    },
    getIData (id, n = 1) {
      if (!id) { return false }
      qa({id: id, pagenum: String(n)}).then(({data}) => {
        if (Object.keys(data).includes('msg')) {
          this.$notify({
            title: '获取数据失败,正在重试',
            position: 'top-right',
            message: data.msg || '请重试',
            type: 'error'
          })
        } else {
          let obj = {
            name: data[0].list.s_qstarr[0].qustion.substring(0, 15) + '...',
            tip: data[0].list.s_qstarr[0].keywords.substring(0, 8) + '...',
            tid: data[0].list._id,
            x: this.EDataArr[1].x,
            y: this.EDataArr[1].y,
            value: 25,
            category: 1,
            isnode: true
          }
          /* 填充当前ID信息 */
          if (this.EData.series[0].data.some(s => s.name === obj.name)) {
          } else {
            this.EData.series[0].data.push(obj)
          }
          /* 填充父级 */
          data[0].flist.forEach(v => {
            let tempY = this.EDataArr[0].min
            let temp = {
              name: v.s_qstarr[0].qustion.substring(0, 15) + '...',
              tip: v.s_qstarr[0].keywords.substring(0, 8) + '...',
              tid: v._id,
              x: this.EDataArr[0].x,
              y: tempY,
              category: 0,
              isnode: true
            }
            if (this.EData.series[0].data.some(s => s.name === temp.name)) {
            } else {
              this.EData.series[0].data.push(temp)
              this.EDataArr[0].min = this.EDataArr[0].min - this.EDataArr[0].step
            }
            this.EData.series[0].links.push({
              source: temp.name,
              target: obj.name,
              lineStyle: {
                normal: {
                  curveness: 0.1
                }
              },
              islink: true
            })
          })
          /* 填充子级 */
          data[0].clist.forEach(v => {
            let tempY = this.EDataArr[2].max
            let temp = {
              name: v.s_qstarr[0].qustion.substring(0, 15) + '...',
              tip: v.s_qstarr[0].keywords.substring(0, 8) + '...',
              tid: v._id,
              x: this.EDataArr[2].x,
              y: tempY,
              category: 2,
              isnode: true
            }
            if (this.EData.series[0].data.some(s => s.name === temp.name)) {
            } else {
              this.EData.series[0].data.push(temp)
              this.EDataArr[2].max = this.EDataArr[2].max + this.EDataArr[2].step
            }
            this.EData.series[0].links.push({
              source: obj.name,
              target: temp.name,
              lineStyle: {
                normal: {
                  curveness: 0.1,
                  color: 'red'
                }
              },
              islink: true
            })
          })
          // 绘制图表
          this.createEcharts()
          if (Math.ceil(data[0].ccount / 10) > n) {
            return this.getIData(id, n + 1)
          }
        }
      }).catch(err => {
        this.$notify({
          title: '获取数据失败,正在重试',
          position: 'top-right',
          message: err || '请重试',
          type: 'error'
        })
      })
    }
  } // 函数
}
</script>
<style lang='scss'>
.amend {
  .my-tip {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .tip-item {
      display: flex;
      flex-direction: row;
      span {
        min-width: 3rem;
        max-width: 3rem;
        text-align: left;
        color: #8c939d;
      }
      span + span {
        min-width: 160px;
        max-width: 160px;
        text-align: center;
        color: black;
        overflow:hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
      }
    }
  }
  .right {
    text-align: right;
  }
  .left {
    text-align: left;
  }
  .drop-text {
    width: 200px;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    text-align: left;
  }
  .my_top {
    margin: 20px 0;
  }
  .my_title {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: 30px 0;
    span.title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  box-sizing: border-box;
  .demo-table-expand {
    text-align: left;
    font-size: 0;
  }
  .el-table {
    text-align: center;
  }
  .c-tag {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .el-form-item{
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      .el-form-item__label{
        max-width: 5rem;
        min-width: 5rem;
      }
    }
  }
  .is-leaf {
    text-align: center;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
}
</style>
